package com.example.home_app.base


import android.Manifest
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.android.base.DontSwipeBack
import com.android.frame.mvp.CommonBaseActivity
import com.example.home_app.R
import com.example.home_app.base.welcome.GuideActivity

import com.example.home_app.databinding.ActivityMainBinding
import com.example.home_app.util.SPTool
import com.example.home_app.util.State
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.permissionx.guolindev.PermissionX
import site.gemus.openingstartanimation.NormalDrawStrategy
import site.gemus.openingstartanimation.OpeningStartAnimation

class MainActivity : CommonBaseActivity<ActivityMainBinding>(), DontSwipeBack {

    private val mImageButton = intArrayOf(
        R.drawable.selector_bottom_frame,
        R.drawable.selector_bottom_widget,
        R.drawable.selector_bottom_util
    )
    private val mFragmentList: MutableList<Fragment> = mutableListOf(
        FrameFragment.newInstance(),
        WidgetFragment.newInstance(),
        UtilFragment.newInstance()
    )
    private val mTitleList: MutableList<String> = mutableListOf("公告", "设备", "工具")

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun handleView(savedInstanceState: Bundle?) {
        intView()
        openApp()
        initBottomNavigationBar()
        requestPower()

    }
    private fun intView(){
        if ( SPTool.getInstance(this)
                ?.getBoolean("isFirstUse", true) == true) {
            startActivity(GuideActivity::class.java)
            finish()
            SPTool.getInstance(this)
                ?.putBoolean("isFirstUse", false)
        }else{
            Handler(Looper.getMainLooper()).postDelayed({
                /**
                 * 数据初始化（200毫秒）
                 * */
                State.DeviceIDs = SPTool.getInstance(this) !!
                    .getString("DeviceIDs", "")
                State.DeviceIDBathroom = SPTool.getInstance(this) !!
                    .getString("DeviceIDBathroom", "")
                State.DeviceIDHome = SPTool.getInstance(this) !!
                    .getString("DeviceIDHome", "")
                State.DeviceIDKitchen = SPTool.getInstance(this) !!
                    .getString("DeviceIDKitchen", "")
            }, 300)


        }
    }
    //初始化底部导航栏
    private fun initBottomNavigationBar() {
//        tab_layout.setTabMode(TabLayout.MODE_FIXED)//不可以轮动
        for (i in mTitleList.indices) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(mTitleList[i]))
        }
        val adapter = object : FragmentPagerAdapter(supportFragmentManager,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

            override fun getItem(i: Int): Fragment = mFragmentList[i]

            override fun getCount(): Int = mTitleList.size

            override fun getPageTitle(i: Int): CharSequence = mTitleList[i]

        }
        binding.viewPager.adapter = adapter
        binding.viewPager.offscreenPageLimit = mFragmentList.size
        binding.tabLayout.setupWithViewPager(binding.viewPager)
        for (i in mFragmentList.indices) {
            val tab = binding.tabLayout.getTabAt(i)
            //添加自定义布局
            tab!!.customView = getTabView(i)
            //默认选中第一个导航栏
            if (i == 0) {
                (tab.customView !!.findViewById(R.id.iv) as ImageView).isSelected = true
                (tab.customView !!.findViewById(R.id.tv) as TextView).isSelected = true
            }
        }

        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            //选中之后再次点击Tab时触发
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            //切换Tab时触发，返回切换前的Tab
            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            //选择某一个Tab时触发，返回切换后的Tab
            override fun onTabSelected(tab: TabLayout.Tab?) {
                //解决ViewPager + Fragment，点击tab切换时造成的闪屏问题
                tab?.let {
                    // 默认切换的时候，会有一个过渡动画，设为false后，取消动画，直接显示
                    binding.viewPager.setCurrentItem(it.position, true)
                }
            }

        })
    }

    @SuppressLint("InflateParams")
    private fun getTabView(position: Int): View {
        val view = LayoutInflater.from(applicationContext).inflate(R.layout.layout_tab_content, null)
        val iv = view.findViewById(R.id.iv) as ImageView
        val tv = view.findViewById(R.id.tv) as TextView
        iv.setImageResource(mImageButton[position])
        tv.text = mTitleList[position]
        return view
    }

    override fun initBar() {
        //隐藏状态栏
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init()
    }

    override fun initListener() {
    }

    //override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater)

    //再按一次退出程序
    private var mLastPressTime: Long = 0

    override fun onBackPressed() {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - mLastPressTime > 2 * 1000) {
            showToast("再按一次退出程序", false)
        } else {
            super.onBackPressed()
        }
        mLastPressTime = currentTimeMillis
    }
    private var openingStartAnimation: OpeningStartAnimation? = null
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("UseCompatLoadingForDrawables")
    private fun openApp() {

        openingStartAnimation = OpeningStartAnimation.Builder(this)
            .setDrawStategy(NormalDrawStrategy())
            .setAppIcon(getDrawable(R.mipmap.ic_launcher_foreground)) //设置图标
            .setColorOfAppIcon(Color.RED) //设置绘制图标线条的颜色
            .setAppName("Hot Home") //设置app名称
            .setColorOfAppName(Color.DKGRAY) //设置app名称颜色
            .setAppStatement("敢想 敢言 敢做") //设置一句话描述
            .setColorOfAppStatement(Color.BLUE) // 设置一句话描述的颜色
            .setAnimationInterval(3000) // 设置动画时间间隔
            .setAnimationFinishTime(500) // 设置动画的消失时长
            .create()
        openingStartAnimation?.show(this)
    }

    /**
     * 动态赋予权限
     */
    private fun requestPower() {
        PermissionX.init(this)
            .permissions(
                Manifest.permission.ACCESS_NETWORK_STATE /*访问网络权限*/,
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION /*GD地图*/,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.BLUETOOTH
            )
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(
                    deniedList,
                    "HomeApp 需要您同意以下授权才能正常使用",
                    "同意",
                    "拒绝"
                )
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    if (! State.Start) {
                        //Toast.makeText(this, "您同意了所有权限!", Toast.LENGTH_SHORT).show();
                        State.Start = true
                    }
                    //createLog4jLocal();
                } else {
                    Toast.makeText(this, "您拒绝了以下权限:$deniedList", Toast.LENGTH_SHORT).show()
                    //finish();
                }
            }
    }
}
